#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>

#define BUF_SIZE 30
void error_handling(char *message);

int main(int argc, char *argv[])
{
    WSADATA wsaData;
    SOCKET sd;
    FILE *fp;

    char buf[BUF_SIZE];
    int read_cnt;
    SOCKADDR_IN serv_adr;

    if (argc != 3)
    {
        printf("Usage : %s <IP> <port>\n", argv[0]);
        exit(1);
    }

    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
		error_handling("WSAStartup() error!");

    fp = fopen("receive.dat", "wb");
    sd = socket(PF_INET, SOCK_STREAM, 0);

    memset(&serv_adr, 0, sizeof(serv_adr));
    serv_adr.sin_family = AF_INET;
    serv_adr.sin_addr.s_addr = inet_addr(argv[1]);
    serv_adr.sin_port = htons(atoi(argv[2]));

    connect(sd, (SOCKADDR*)&serv_adr, sizeof(serv_adr));

    while ((read_cnt = recv(sd, buf, BUF_SIZE, 0)) != 0)
        fwrite((void *)buf, 1, read_cnt, fp);

    puts("Received file data");
    send(sd, "Thank you", 10, 0);
    fclose(fp);
    closesocket(sd);
    WSACleanup();

    return 0;
}

void error_handling(char *message)
{
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}